package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.Student;
import com.xmy.cultivate.entity.TypeValueData;
import com.xmy.cultivate.entity.WecharsBind;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.StaffMapper;
import com.xmy.cultivate.mapper.StudentMapper;
import com.xmy.cultivate.mapper.TypeValueDataMapper;
import com.xmy.cultivate.mapper.WecharsBindMapper;
import com.xmy.cultivate.service.IStaffService;
import com.xmy.cultivate.service.IWecharsBindService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 微信绑定 服务实现类
 * </p>
 *
 * @author min
 * @since 2023-01-12
 */
@Service
public class WecharsBindServiceImpl extends ServiceImpl<WecharsBindMapper, WecharsBind> implements IWecharsBindService {

    @Autowired
    WecharsBindMapper wecharsBindMapper;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    TypeValueDataMapper typeValueDataMapper;

    @Autowired
    @Lazy
    StaffMapper staffMapper;

    /**
     *
     * @return
     */
    public String addPhone(WecharsBind wecharsBind){
//        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
//        studentQueryWrapper.eq("linkman_phone",wecharsBind.getPhone());
//        List<Student> studentList = studentMapper.selectList(studentQueryWrapper);



        // 后台员工手机号验证
        Integer staffCount = staffMapper.staffCountByPhone(wecharsBind.getPhone().trim());
        if (staffCount != null && staffCount > 0) {
            return "教师手机号无法绑定学员";
//            throw new CommonException(ResultCode.PHONE_IS_TEACHER);
        }

        // 手机号绑定次数验证
        /*Integer studentCount = typeValueDataMapper.studentCountByPhone(wecharsBind.getPhone().trim());
        if (studentCount != null && studentCount >= 2) {
            return "绑定失败，一个手机号只能绑定2个学员，如有需要绑定更多个，请与管理员联系";
        }*/

        List<WecharsBind> wecharsBindList = wecharsBindMapper.getWecharsBindCount(wecharsBind.getOpenid());
        if (wecharsBindList.size() >= 2) {
            List<String> names = new ArrayList<>();
            for (WecharsBind wecharsBind1 : wecharsBindList) {
                names.add(wecharsBind1.getStudentName().trim());
            }
            return "已成功绑定："+String.join(",", names)+",如需绑定更多学员，请与管理员联系";
        }

        List<TypeValueData> typeValueDataList = typeValueDataMapper.getTypeValueData(wecharsBind.getPhone());

        List<String> rightNameList = new ArrayList<>();//绑定成功
        List<String> errorNameList = new ArrayList<>();//绑定失败
        for (TypeValueData typeValueData:typeValueDataList){
            QueryWrapper<WecharsBind> wecharsBindQueryWrapper = new QueryWrapper<>();
            wecharsBindQueryWrapper.eq("openid",wecharsBind.getOpenid());
            wecharsBindQueryWrapper.eq("phone",wecharsBind.getPhone());
//            wecharsBindQueryWrapper.eq("student_id",student.getId());
            wecharsBindQueryWrapper.eq("student_id",typeValueData.getForId());
            Long count = wecharsBindMapper.selectCount(wecharsBindQueryWrapper);

            if(count.equals(0L)){
                wecharsBind.setStudentId(typeValueData.getForId());
                wecharsBind.setCreatedAt(LocalDateTime.now().withNano(0));
                wecharsBindMapper.insert(wecharsBind);
                Student student = studentMapper.selectById(typeValueData.getForId());
                if (student!=null){
                    student.setIsGuanzhu(1);
                    studentMapper.updateById(student);
                }
                rightNameList.add(typeValueData.getStudentName());
            }else {
                Student student = studentMapper.selectById(typeValueData.getForId());
                if (student!=null){
                    student.setIsGuanzhu(1);
                    studentMapper.updateById(student);
                }
                rightNameList.add(typeValueData.getStudentName());
            }
        }

        String rs = "";
        if (rightNameList.size()>0){
            String studentStr = rightNameList.stream().map(String::valueOf).collect(Collectors.joining(","));
            rs = "绑定成功："+studentStr;
        }
        if (errorNameList.size()>0){
            String studentStr = errorNameList.stream().map(String::valueOf).collect(Collectors.joining(","));
            if (rs != ""){
                rs +="；";
            }
            rs += studentStr+"已被绑定，请联系管理员调整";
        }
        return rs;
    }

    public List<String> studentList(String openid){
        QueryWrapper<WecharsBind> wecharsBindQueryWrapper = new QueryWrapper<>();
        wecharsBindQueryWrapper.eq("openid",openid);
        List<WecharsBind> wecharsBindList = wecharsBindMapper.selectList(wecharsBindQueryWrapper);
        List<String> studentNameList = new ArrayList<>();
        for (WecharsBind wecharsBind:wecharsBindList){
            Student student = studentMapper.selectById(wecharsBind.getStudentId());
            if(student !=null){
                studentNameList.add(student.getName());
            }
        }
        return studentNameList;
    }

    public boolean studentDelete(String openid){
        QueryWrapper<WecharsBind> wecharsBindQueryWrapper = new QueryWrapper<>();
        wecharsBindQueryWrapper.eq("openid",openid);
        Integer rs = wecharsBindMapper.delete(wecharsBindQueryWrapper);
        return rs>1?true:false;
    }
}
